<?php
// ========================== 文件说明 ==========================//
// 本文件说明：案例库管理
// --------------------------------------------------------------//
// 本程序作者：黄进
// --------------------------------------------------------------//
// 本程序版本：SaBlog-X Plus Ver 2.0
// --------------------------------------------------------------//
// 本程序主页：http://www.sablog.net
// ========================== 开发环境 ==========================//
// register_globals = Off
// --------------------------------------------------------------//
// magic_quotes_gpc = On
// --------------------------------------------------------------//
// safe_mode = On
// --------------------------------------------------------------//
// Windows server 2003 & Linux & FreeBSD
// --------------------------------------------------------------//
// Apache/1.3.33 & PHP/4.3.2 & MySQL/4.0.17
// --------------------------------------------------------------//
// Apache/1.3.34 & PHP/4.4.1 & MySQL/5.0.16
// --------------------------------------------------------------//
// Apache/2.0.55 & PHP/5.1.1 & MySQL/5.0.15
// --------------------------------------------------------------//
// Copyright (C) Security Angel Team All Rights Reserved.
// ==============================================================//

if(!defined('SABLOG_ROOT') || !isset($php_self) || !preg_match("/[\/\\\\]cp\.php$/", $php_self)) {
	exit('Access Denied');
}

// 加载附件相关函数
require_once(SABLOG_ROOT.'include/func/attachment.func.php');

$uquery = '';
if ($sax_group != 1) {
	$uquery = " AND uid='$sax_uid'";
}

!$action && $action = 'list';

$catedb = array();
$query = $DB->query("SELECT cid,name FROM {$db_prefix}categories ORDER BY displayorder");
while ($cate = $DB->fetch_array($query)) {
	$catedb[$cate['cid']] = $cate['name'];
}
unset($cate);
$DB->free_result($query);

if($_POST['action'] == 'addcase') {
	// 取值并过滤部分
	$title        = trim($_POST['title']);
	$description  = sax_addslashes($_POST['description']);
	$university     = strtolower(sax_addslashes(trim($_POST['university'])));
	$keywords     = $university .','. strtolower(sax_addslashes(trim($_POST['keywords'])));
	$visible     = intval($_POST['visible']);
	// 时间变量
	$edittime    = intval($_POST['edittime']);
	$newyear     = intval($_POST['newyear']);
	$newmonth    = intval($_POST['newmonth']);
	$newday      = intval($_POST['newday']);
	$newhour     = intval($_POST['newhour']);
	$newmin      = intval($_POST['newmin']);
	$newsec      = intval($_POST['newsec']);

	$keywords    = str_replace('，', ',', $keywords);
	$keywords    = str_replace(',,', ',', $keywords);
	if (substr($keywords, -1) == ',') {
		$keywords = substr($keywords, 0, strlen($keywords)-1);
	}

	// 暂时把提交的数据保存到COOKIE
	// 2880分钟=2天
	scookie('title',$title,2880);
	scookie('description',$description,2880);
	scookie('keywords',$keywords,2880);
	scookie('visible',$visible,2880);

	// 检查变量
	checktitle($title);
	checkcontent($description);
	checkkeywords($keywords);

	$title = char_cv($title);
	$r = $DB->fetch_one_array("SELECT caseid FROM {$db_prefix}caselib WHERE title='$title' and description='$description'  LIMIT 1");
	if ($r) {
		redirect('数据库中已存在相同的数据', 'cp.php?job=article&action=add');
	}
	// 上传附件
	$searcharray = array();
	$replacearray = array();
	$uploadstat = 'caselib';
	$casefilename = '';
	$casefiletype = '';
	$casefilesize = '';
	require_once(SABLOG_ROOT.'admin/uploadfiles.php');
	// 上传结束

	// 修改时间
	if ($edittime) {
		if (checkdate($newmonth, $newday, $newyear)) {
			if (substr(PHP_OS, 0, 3) == 'WIN' && $newyear < 1970) {
				$posttime = $timestamp;
			} else {
				$posttime = gmmktime($newhour, $newmin, $newsec, $newmonth, $newday, $newyear) - $timeoffset * 3600;
			}
		} else {
			$posttime = $timestamp;
		}
	} else {
		$posttime = $timestamp;
	}

	// 插入数据部分
    $DB->query("INSERT INTO {$db_prefix}caselib (title, description, keywords, dateline, filename, filetype, filesize, downloads, filepath, visible) VALUES ('$title', '$description', '$keywords', '$posttime', '$casefilename', '$casefiletype', '$casefilesize', '0', '".sax_addslashes($filepath)."', '$visible')");
	$caseid = $DB->insert_id();

/*	$DB->unbuffered_query("UPDATE {$db_prefix}users SET articles=articles+1 WHERE userid='$sax_uid'");
	if($attachmentids){
		$DB->unbuffered_query("UPDATE {$db_prefix}attachments SET articleid='$articleid' WHERE attachmentid IN($attachmentids)");
	}
	if ($searcharray && $replacearray) {
		$content = str_replace($searcharray, $replacearray, $content);
		$DB->query("UPDATE {$db_prefix}articles SET content='$content' WHERE articleid='$articleid'");
	}*/
	// 插入/更新Tags
	if ($keywords) {
		$tagdb = explode(',', $keywords);
		foreach($tagdb as $tag) {
			$aids = '';
			$tag = sax_addslashes(trim($tag));
			if ($tag) {
				$r  = $DB->fetch_one_array("SELECT tagid,caseids FROM {$db_prefix}tags WHERE tag='$tag' LIMIT 1");
				if(!$r) {
					$DB->query("INSERT INTO {$db_prefix}tags (tag,usenum,caseids) VALUES ('$tag', '1', '$caseid')");
					$DB->unbuffered_query("UPDATE {$db_prefix}statistics SET tag_count=tag_count+1");
				} else {
					$caseid = $r['caseids'].','.$caseid;
					$DB->unbuffered_query("UPDATE {$db_prefix}tags SET usenum=usenum+1, caseids='$caseid' WHERE tag='$tag'");
				}
			}
		}
	}
	// 更新案例数量
	$DB->unbuffered_query("UPDATE {$db_prefix}statistics SET case_count=case_count+1");
	hottags_recache();
	statistics_recache();

	$cookiedb = array('title','description','keywords','visible');
	dcookies($cookiedb);
    redirect('添加案例成功', 'cp.php?job=caselib&action=add');
}

if (in_array($action, array('add', 'mod'))) {
	if ($action == 'mod') {
		$act = 'modcase';
		$tdtitle = '修改案例';
		$caseid = intval($_GET['caseid']);
		$case = $DB->fetch_one_array("SELECT * FROM {$db_prefix}caselib
			WHERE caseid='$caseid'");
		if (empty($article)) {
			redirect('案例不存在');
		}
		$case['keywords'] = htmlspecialchars($case['keywords']);
		$case['description'] = str_replace('\r\n', '', $case['description']);

		//附件
		$query = $DB->query("SELECT caseid,dateline,filename,filesize FROM {$db_prefix}caselib WHERE caseid = '".$case['caseid']."'");
		$attachdb = array();
		while($attach = $DB->fetch_array($query)) {
			$attach['filename'] = htmlspecialchars($attach['filename']);
			$attach['dateline'] = sadate('Y-m-d H:i:s',$attach['dateline']);
			$attach['filesize'] = sizecount($attach['filesize']);
			$attachdb[] = $attach;
		}
		unset($attach);

		$visible_check = $article['visible'] ? 'checked' : '';
		
	} else {
		$act = 'addcase';
		$tdtitle = '添加案例';
		$case['description'] = '';
		$case['visible'] = isset($_COOKIE['visible']) ? intval($_COOKIE['visible']) : '1';
		$visible_check = 'checked';
	}
}
if ($action == 'list') {
	$m = $_GET['m'] ? $_GET['m'] : $_POST['m'];

	$addquery = $pagelink = '';
	$subnav = '全部案例';
	if ($sax_group != 1) {
		$subnav = '您上传的全部案例';
	}
	if ($_GET['tag']) {
		$item = sax_addslashes($_GET['tag']);
		$tag = $DB->fetch_one_array("SELECT caseids FROM {$db_prefix}tags WHERE tag='$item' LIMIT 1");
		if (!$tag) {
			redirect('标签不存在', 'cp.php?job=caselib&action=list');
		}
		$addquery .= " AND a.articleid IN (".$tag['caseids'].")";
		$subnav = 'Tags:'.$item;
		$pagelink .= '&tag='.urlencode($item);
	}
	if ($view == 'stick') {
		$addquery .= " AND stick='1'";
		$subnav = '置顶的日志';
		$pagelink .= '&view=stick';
	} elseif ($view == 'hidden') {
		$addquery .= " AND visible='0'";
		$subnav = '隐藏的日志';
		$pagelink .= '&view=hidden';
	} elseif ($view == 'display') {
		$addquery .= " AND visible='1'";
		$subnav = '显示的日志';
		$pagelink .= '&view=display';
	}
	if ($m) {
		$mdb = explode('-', $m);
		list($start, $end) = explode('-', gettimestamp($mdb[0],$mdb[1]));
		$pagelink .= '&m='.$m;
		$subnav = '在'.$mdb[0].'年'.$mdb[1].'月里';
		//*******************************//
		$addquery .= " AND dateline >= '".correcttime($start)."' AND dateline < '".correcttime($end)."' ";
	}
	// 搜索部分
	$keywords = sax_addslashes(trim($_POST['keywords'] ? $_POST['keywords'] : $_GET['keywords']));
	if ($keywords) {
		$keywords = str_replace("_","\_",$keywords);
		$keywords = str_replace("%","\%",$keywords);
		if(preg_match("(AND|\+|&|\s)", $keywords) && !preg_match("(OR|\|)", $keywords)) {
			$andor = ' AND ';
			$sqltxtsrch = '1';
			$keywords = preg_replace("/( AND |&| )/is", "+", $keywords);
		} else {
			$andor = ' OR ';
			$sqltxtsrch = '0';
			$keywords = preg_replace("/( OR |\|)/is", "+", $keywords);
		}
		$keywords = str_replace('*', '%', addcslashes($keywords, '%_'));
		foreach(explode("+", $keywords) AS $text) {
			$text = trim($text);
			if($text) {
				$sqltxtsrch .= $andor;
				$sqltxtsrch .= "(description LIKE '%".$text."%' OR title LIKE '%".$text."%')";
			}
		}
		$addquery .= " AND ($sqltxtsrch)";
		$subnav = '搜索结果';
		$pagelink .= '&keywords='.urlencode($keywords);
	}

	$pagenum = 20;
	if($page) {
		$start_limit = ($page - 1) * $pagenum;
	} else {
		$start_limit = 0;
		$page = 1;
	}
	$rs = $DB->fetch_one_array("SELECT * FROM {$db_prefix}caselib WHERE 1 $addquery");
	$total = $rs['caselib'];
	$multipage = multi($total, $pagenum, $page, 'cp.php?job=caselib&action=list'.$pagelink);

	$query = $DB->query("SELECT caseid,title,dateline,downloads,visible,permission FROM {$db_prefix}caselib WHERE 1 $addquery ORDER BY dateline DESC LIMIT $start_limit, $pagenum");

	$casedb = array();
    while ($case = $DB->fetch_array($query)) {
		$case['dateline'] = sadate('Y-m-d H:i',$case['dateline']);
		$casedb[] = $case;
	}
	unset($case);
	$DB->free_result($query);

}
cpheader($subnav);
include template('caselib');
?>